<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
<el-col :span="1.5"><el-button type="primary" plain logo="el-logo-plus" size="mini" @click="handleAdd" v-hasPermi="['mapp:park:add']">新增</el-button></el-col>
<el-col :span="1.5"><el-button type="success" plain logo="el-logo-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['mapp:park:edit']">修改</el-button></el-col>
<el-col :span="1.5"><el-button type="danger" plain logo="el-logo-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['mapp:park:remove']">删除</el-button></el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
    </el-row>
    <el-table v-loading="loading" :data="comList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户" align="center" prop="nickName" width="155"show-overflow-tooltip/>
      <el-table-column label="项目" align="center" prop="projectname" width="155"show-overflow-tooltip/>
      <el-table-column label="编号" align="center" prop="id" width="55"/>
      <el-table-column label="景区图片logo" align="center" prop="logo" show-overflow-tooltip/>
      <el-table-column label="景区MP3播报文件" align="center" prop="mp3" show-overflow-tooltip/>
      <el-table-column label="景区详情" align="center" prop="parkInfo" show-overflow-tooltip/>
      <el-table-column label="景区图片/视频" align="center" prop="parkText" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="185">
        <template slot-scope="scope">
<!-- <el-button size="mini" type="text" logo="el-logo-view" @click="openDetailDialog(scope.row.id)">查看</el-button> -->
<el-button size="mini" type="text" logo="el-logo-edit" @click="handleUpdate(scope.row)" v-hasPermi="['mapp:park:edit']">修改</el-button>
<el-button size="mini" type="text" logo="el-logo-delete" @click="handleDelete(scope.row)" v-hasPermi="['mapp:park:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
    <el-dialog :title="title" :visible.sync="open" width="1080px" append-to-body>
      <div class="scrollable-content">
      <el-form ref="form" :model="form" :rules="rules" label-width="102px">
        <el-form-item label="客户名称" prop="customerId">
          <el-select v-model="form.customerId" placeholder="请选择客户名称" filterable style="width:100%" @change="handleNicknameChange">
            <el-option v-for="item in options" :key="item.userId" :label="item.nickName" :value="item.userId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目名称" filterable style="width:100%" @change="handleProjectnameChange">
            <el-option v-for="item in projectnameOptions" :key="item.id" :label="item.projectname" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="景区图片logo" prop="logo">
          <imgUpload v-model="form.logo" style="width:100%"/>
        </el-form-item>
        <el-form-item label="景区MP3播报" prop="mp3">
          <audiooUpload v-model="form.mp3" style="width:100%"/>
        </el-form-item>
        <!-- <el-form-item label="景区详情" prop="parkInfo">
          <el-input v-model="form.parkInfo" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="景区图片/视频" prop="parkText">
          <fileUpload v-model="form.parkText" style="width:100%"/>
        </el-form-item> -->
        <el-form-item label="景区介绍">
            <editor v-model="form.parkText" :min-height="192" />
        </el-form-item>
      </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button><el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog :title="title" :visible.sync="openDetail" width="1280px" append-to-body>
        <div v-loading="loadingDetail" class="scrollable-content content">
          <el-form ref="form" :model="form" label-width="78px">
            <el-form-item label="客户名称">
              <el-select v-model="form.customerId" placeholder="请选择客户名称" filterable style="width:100%" disabled>
                <el-option v-for="item in options" :key="item.userId" :label="item.nickName" :value="item.userId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="项目名称">
              <el-select v-model="form.projectId" placeholder="请选择项目名称" filterable style="width:100%" disabled>
                <el-option v-for="item in projectnameOptions" :key="item.id" :label="item.projectname" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-form>
          <div v-html="form.parkText"></div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="closeDetail"> 关 闭 </el-button>
        </div>
    </el-dialog> -->
  </div>
</template>
<script>
import { listCom, getCom, delCom, addCom, updateCom } from "@/api/iot/park";
import { listUser } from '@/api/iot/tool'
import { listProject } from '@/api/iot/faproject'
export default {
  name: "Park",
  data() {
    return {
      loadingDetail: false,
      openDetail: false,
      options: [],
      projectnameOptions: [],
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      comList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        logo: null,
        mp3: null,
        parkInfo: null,
        parkText: null
      },
      form: {},
      rules: {
        customerId: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
        projectId: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        // parkText: [{ required: true, message: "景区介绍不能为空！", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
    this.fetchUsers();
    this.fetchProjectnames();
  },
  methods: {
    handleNicknameChange(selectedId) {
      const selectedOption = this.options.find(option => option.userId === selectedId);
      if (selectedOption) {
        this.form.customerId = selectedOption.userId;    // 将选择的 userId 存入 adminId 字段
      }
    },
    handleProjectnameChange(selectedId) {
      const selectedOption = this.projectnameOptions.find(option => option.id === selectedId);
      if (selectedOption) {
        this.form.projectId = selectedOption.id;
      } else {
        console.error('No matching data found for value:', value);
      }
    },
    async fetchUsers() {
      try {
        const response = await listUser();
        var resList=response.rows;
        if (response && resList) {
          this.options = resList.map(user => ({
            userId: user.userId,
            nickName: user.nickName
          }));
        }
      } catch (error) {
        console.error('获取用户列表失败', error);
      }
    },
    async fetchProjectnames() {
      try {
        const response = await listProject();
        var resList=response.rows;
        if (response && resList) {
          this.projectnameOptions = resList.map(item => ({
            id: item.id,  // 用于存储的项目 ID
            projectname: item.projectname,  // 用于展示的项目名称
          }));
          console.log("获取项目名称", this.projectnameOptions);
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    closeDetail() {
        this.openDetail = false;
        this.reset();
    },
    openDetailDialog(id) {
        this.title = "景区详解";
        this.openDetail = true;
        this.loadingDetail = true;
        getCom(id).then(response => {
            this.form = response.data;
            this.openDetail = true;
            this.loadingDetail = false;
        });
    },
    getList() {
      this.loading = true;
      listCom(this.queryParams).then(response => {
        this.comList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        customerId: null,
        projectId: null,
        id: null,
        logo: null,
        mp3: null,
        parkInfo: null,
        parkText: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增-景区";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCom(id).then(response => {
        var datarerult = response.data;
        this.form = datarerult;
        var logo = datarerult.logo;
        var mp3 = datarerult.mp3;
        // 处理图标路径
        if (logo && logo.includes('/profile')) {
          this.form.logo = logo.substring(logo.indexOf('/profile'));
        } else {
          this.form.logo = logo;
        }
        // 处理MP3路径
        if (mp3 && mp3.includes('/profile')) {
          this.form.mp3 = mp3.substring(mp3.indexOf('/profile'));
        } else {
          this.form.mp3 = mp3;
        }
        // 处理HTML数据（修复了contain为includes，join为join的正确用法）
        // var parkText = datarerult.parkText;
        // if (parkText && parkText.includes(',')) {
        //   var parkTextArray = parkText.split(',');
        //   var parkTextresult = [];
        //   for (var i = 0; i < parkTextArray.length; i++) {
        //     var item = parkTextArray[i];
        //     if (item && item.includes('/profile')) {
        //       parkTextresult.push(item.substring(item.indexOf('/profile')));
        //     } else {
        //       parkTextresult.push(item);
        //     }
        //   }
        //   this.form.parkText = parkTextresult.join(',');
        // } else if (parkText && parkText.includes('/profile')) {
        //   this.form.parkText = parkText.substring(parkText.indexOf('/profile'));
        // } else {
        //   this.form.parkText = parkText;
        // }
        this.open = true;
        this.title = "修改-景区";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除景区介绍编号为"' + ids + '"的数据项？').then(function() {
        return delCom(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
<style>
.scrollable-content {
  max-height: 80vh;   /* 或固定像素值如 600px */
  overflow-y: scroll;  /* 改为scroll，始终显示滚动条 */
  padding-right: 10px; /* 避免滚动条遮挡内容 */
}
.scrollable-content::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
}
.scrollable-content::-webkit-scrollbar-track {
  background: #f1f1f1; /* 滚动条轨道颜色 */
  border-radius: 4px;
}
.scrollable-content::-webkit-scrollbar-thumb {
  background: #c0c0c0; /* 滚动条滑块颜色 */
  border-radius: 4px;
}
.scrollable-content::-webkit-scrollbar-thumb:hover {
  background: #a0a0a0; /* 滚动条滑块悬停颜色 */
}
</style>
